<script>
	import { Notyf } from 'notyf';
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
  import { now } from '@svelteuidev/composables';


	let notyf;

	let name, pwd;

	let conn, msg;

	let login = (e) => {
		fetch(`/api/login?name=${name}&pwd=${pwd}`)
			.then((v) => v.json())
			.then((v) => {
				if (v.status !== 0) {
					console.log(v.status)
					console.log(v.msg)
					notyf.error('login failed');
					return;
				}

				notyf.success('login success');
			})
			.catch((e) => {
				if (!e.message) {
					console.log(e);
				} else {
					notyf.error(e.message);
				}
			});
	};
	let nowmsg = ' ';
	let nowuser = ' ';
	let nowsay = ' '; 
	onMount(() => {
		notyf = new Notyf({
			duration: 3000,
			className: 'x-notification',
			position: { x: 'right', y: 'top' }
		});

		fetch('/api/session')
			.then((v) => v.json())
			.then((v) => {
				if (v.status !== 0) {
					notyf.error(v.msg);
					return;
				}
				//conn = new WebSocket('ws://' + document.location.host + '/api/msg');
				conn = new WebSocket('ws://localhost:6616/api/msg');
				//conn = new WebSocket('ws://localhost:6616/api/msg', 
					//"{ origin: localhost:8080 }");
				conn.onclose = (e) => notyf.success('conn closed');
				conn.onmessage = (e) => {
					//notyf.success(e.data);
					nowmsg = JSON.parse(e.data)
					console.log(nowmsg)
					nowuser = nowmsg.name
					nowsay = nowmsg.msg
				};
				conn.onopen = (e) => notyf.success('connected');
				conn.onerror = (e) => notyf.error(e.data);
			})
			.catch((e) => {
				if (!e.message) {
					console.log(e);
				} else {
					notyf.error(e.message);
				}
			});

	});

	let sendMsg = (e) => {
		if (!conn) {
			notyf.error('login first');
			return;
		}
		conn.send(msg);
		msg = '';
	}
</script>

<div class="main">
	<div class="title h1">login</div>
	<div>
		name: <input class="input" bind:value={name} type="text" />
	</div>
	<div>
		pwd: <input class="input" bind:value={pwd} type="password" />
	</div>
	<div>
		<button class="button is-primary" on:click={login}>login</button>
		<button class="button" on:click={(e) => goto('/user')}>user mangement</button>
		<button class="button" on:click={(e) => goto('/List')}>topicList</button>
		<!-- <button class="button" on:click={(e) => goto('/register')}>register</button> -->
	</div>
	<div>
		<input on:change={sendMsg} type="text" class="input" size="32" bind:value={msg} />
	</div>
	<p> {nowuser}:{nowsay}</p>
</div>

<style lang="scss">
	@import 'notyf/notyf.min.css';
	@import 'bulma/css/bulma.css';

	.main {
		display: flex;
		flex-direction: column;
		align-items: center;

			div {
				padding: 1em;
			}

			.input {
				width: unset;
				max-width: unset;
			}
	}
</style>